package com.feilong.cn.mybatis.autoV2.session;


import com.feilong.cn.mybatis.autoV2.config.AutoConfiguration;
import com.feilong.cn.mybatis.autoV2.executor.BaseExecutor;
import com.feilong.cn.mybatis.autoV2.executor.IExecutor;
import com.feilong.cn.mybatis.autoV2.proxy.MapperProxy;

import java.lang.reflect.Proxy;

/**
 * Created by yangxulong on 2018/4/2.
 */
public class AutoSqlSession {

    private AutoConfiguration configuration;
    private IExecutor executor;

    public AutoSqlSession(AutoConfiguration configuration) throws ClassNotFoundException {
        this.configuration = configuration;
        //生成Executor时注入插件
        IExecutor executor = new BaseExecutor(this);
        this.executor = (IExecutor) configuration.getInterceptorChain().PluginAll(executor);
        //生成session时要初始化config配置项
        configuration.initMappedStatement();
    }

    public AutoSqlSession(AutoConfiguration configuration, IExecutor executor) throws ClassNotFoundException {
        this.configuration = configuration;
        this.executor = executor;
        configuration.initMappedStatement();
    }

    public <T> T GetMapper(Class clazz) {
        configuration.addMappedStatement(clazz);
        MapperProxy proxy = new MapperProxy(this);
        return (T) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{clazz}, proxy);
    }

    //stateMent 为namespace+id
    public <T> T SelectOne(String stateMent, Object parameter) {
        return this.executor.doQuery(stateMent, parameter);
    }

    public AutoConfiguration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(AutoConfiguration configuration) {
        this.configuration = configuration;
    }

}
